package com.py.inrejected.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.py.api.PyCodeApi;
import com.py.api.PyPurchaseApi;
import com.py.inrejected.domain.OdRejectedDetails;
import com.py.inrejected.domain.PyAttachment;
import com.py.inrejected.domain.SysUser;
import com.py.inrejected.mapper.OdInRejectedMapper;
import com.py.inrejected.message.MessageProducer;
import com.py.inrejected.service.IPyAttachmentService;
import com.py.inrejected.service.PurchrseRejectedVoService;
import com.py.inrejected.service.RejectedInfoService;
import com.py.inrejected.vo.OdPurchaseDetails;
import com.py.inrejected.vo.PurchrseRejectedVo;
import com.ruoyi.common.security.utils.SecurityUtils;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.py.inrejected.domain.OdInRejected;
import com.py.inrejected.service.IOdInRejectedService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 进货退货Controller
 * 
 * @author 童佳
 * @date 2024-12-05
 */
@RestController
@RequestMapping("/inrejected")
public class OdInRejectedController extends BaseController
{
    @Autowired
    private IOdInRejectedService odInRejectedService;

    @Resource
    private PurchrseRejectedVoService purchrseRejectedVoService;

    @Resource
    private IPyAttachmentService pyAttachmentService;

    @Resource
    private RejectedInfoService rejectedInfoService;


    @Resource
    private PyCodeApi pyCodeApi;

    @Resource
    private MessageProducer messageProducer;



    /**
     * 获取编码
     */
    @PostMapping("/getcode")
    public Map<String, Object> getCode(@RequestParam(value = "code",required = false) Integer code){
        System.out.println("进来了"+code);
        return pyCodeApi.generateCode(code);
    }

    /**
     * 查询进货退货列表
     */
    @RequiresPermissions("inrejected:inrejected:list")
    @GetMapping("/list")
    public TableDataInfo list(OdInRejected odInRejected)
    {
        startPage();
        List<OdInRejected> list = odInRejectedService.selectOdInRejectedList(odInRejected);
        return getDataTable(list);
    }

    /**
     * 导出进货退货列表
     */
    @RequiresPermissions("inrejected:inrejected:export")
    @Log(title = "进货退货", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OdInRejected odInRejected)
    {
        List<OdInRejected> list = odInRejectedService.selectOdInRejectedList(odInRejected);
        ExcelUtil<OdInRejected> util = new ExcelUtil<OdInRejected>(OdInRejected.class);
        util.exportExcel(response, list, "进货退货数据");
    }

    /**
     * 获取进货退货详细信息
     */
    @RequiresPermissions("inrejected:inrejected:query")
    @GetMapping(value = "/{prId}")
    public AjaxResult getInfo(@PathVariable("prId") Integer prId)
    {
        return success(odInRejectedService.selectOdInRejectedByPrId(prId));
    }

    /**
     * 新增进货退货
     */
    @RequiresPermissions("inrejected:inrejected:add")
    @Log(title = "进货退货", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OdInRejected odInRejected)
    {
        System.out.println("odInRejected："+odInRejected);
        System.out.println("number:"+odInRejected.getNumber());
        System.out.println("codeId:"+odInRejected.getCodeId());
        pyCodeApi.saveCode(odInRejected.getCodeId(),odInRejected.getNumber());
        odInRejected.setCreateBy(SecurityUtils.getUsername());
        SysUser sysUser=odInRejectedService.selectBySysUserName(SecurityUtils.getUsername());
        odInRejected.setCreateDept(sysUser.getDeptName());
        odInRejected.setCreateTime(new Date());
        odInRejected.setPrState("0");
        odInRejected.setIsDel("0");
        List<Object> fileList = odInRejected.getFileList();
        if(fileList.size()>0){
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    Object ob=fileMap.get("size");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            String name = (String) data.get("name");
                            String url = (String) data.get("url");
                            System.out.println("Name: " + name);
                            System.out.println("URL: " + url);
                            PyAttachment pyAttachment=new PyAttachment();
                            pyAttachment.setBusinessType("进货退货单");
                            pyAttachment.setOwnershipNumber(odInRejected.getPrCode());
                            pyAttachment.setFileName(name);
                            pyAttachment.setSize(Long.parseLong(ob.toString()));
                            pyAttachment.setFilePath(url);
                            pyAttachmentService.insertPyAttachment(pyAttachment);
                        }
                    }
                }
            }
        }
        messageProducer.sendMessageDirect("新增了一个进货退货单: "+odInRejected.getPrCode()+" 待审核!");
        /*return null;*/
        return toAjax(odInRejectedService.insertOdInRejected(odInRejected));
    }

    /**
     * 修改进货退货
     */
    @RequiresPermissions("inrejected:inrejected:edit")
    @Log(title = "进货退货", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OdInRejected odInRejected)
    {
        odInRejected.setUpdateBy(SecurityUtils.getUsername());
        odInRejected.setUpdateTime(new Date());
        pyAttachmentService.deletePyAttachmentByOwnershipNumber(odInRejected.getPrCode());
        List<Object> fileList = odInRejected.getFileList();
        if (fileList.size() > 0) {
            System.out.println("进来了11111111111111");
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    String name = (String) fileMap.get("name");
                    String url = (String) fileMap.get("url");
                    Object size = fileMap.get("size");

                    // 如果 name 和 url 不为空，直接使用
                    if (name != null && url != null) {
                        System.out.println("Name: " + name);
                        System.out.println("URL: " + url);
                        PyAttachment pyAttachment = new PyAttachment();
                        pyAttachment.setBusinessType("进货退货单");
                        pyAttachment.setOwnershipNumber(odInRejected.getPrCode());
                        pyAttachment.setFileName(name);
                        pyAttachment.setSize(Long.parseLong(size.toString()));
                        pyAttachment.setFilePath(url);
                        pyAttachmentService.insertPyAttachment(pyAttachment);
                        continue;
                    }

                    // 如果 name 或 url 为空，尝试从 response 中获取
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            name = (String) data.get("name");
                            url = (String) data.get("url");
                            if (name != null && url != null) {
                                System.out.println("Name: " + name);
                                System.out.println("URL: " + url);
                                PyAttachment pyAttachment = new PyAttachment();
                                pyAttachment.setBusinessType("进货退货单");
                                pyAttachment.setOwnershipNumber(odInRejected.getPrCode());
                                pyAttachment.setFileName(name);
                                pyAttachment.setSize(Long.parseLong(size.toString()));
                                pyAttachment.setFilePath(url);
                                pyAttachmentService.insertPyAttachment(pyAttachment);
                            }
                        }
                    }
                }
            }
        }
        return toAjax(odInRejectedService.updateOdInRejected(odInRejected));
    }

    /**
     * 删除进货退货
     */
    @RequiresPermissions("inrejected:inrejected:remove")
    @Log(title = "进货退货", businessType = BusinessType.DELETE)
	@DeleteMapping("/{prIds}")
    public AjaxResult remove(@PathVariable Integer[] prIds)
    {
        return toAjax(odInRejectedService.deleteOdInRejectedByPrIds(prIds));
    }

    /**
     * 查询所有货品信息
     */
    @RequestMapping("/selectPurchaseRejectProduct")
    public TableDataInfo selectPurchaseRejectProduct(PurchrseRejectedVo purchrseRejectedVo){
        System.out.println("进来近似数:"+purchrseRejectedVo);
        startPage();
        List<PurchrseRejectedVo> list=purchrseRejectedVoService.selectPurchrseRejectedVoList(purchrseRejectedVo);
        list.forEach(System.out::println);
        return getDataTable(list);
    }




    @Transactional(rollbackFor = Exception.class)
    //审核
    @RequiresPermissions("inrejected:inrejected:check")
    @RequestMapping("/check")
    public AjaxResult check(@RequestBody Map<String,Object> map){
        System.out.println("审核的phIds:"+map);
        Map<String,Object> map1=new HashMap<>();
        map1.put("reviewer", SecurityUtils.getUsername());
        map1.put("reviewer_time",new Date());
        if((String)map.get("comments")!=null){
            map1.put("reviewer_report",map.get("comments").toString());
        }
        List<Integer> list= (List<Integer>) map.get("prId");
       /* Object resultObj = map.get("result");
        if ((int) resultObj == 5) {
            list.forEach(l -> {
                System.out.println("进来了吗");
                OdInRejected odInRejected = odInRejectedService.selectOdInRejectedByPrId(l);
                System.out.println("od:" + odInRejected);
                OdRejectedDetails odRejectedDetails = new OdRejectedDetails();
                odRejectedDetails.setPrCode(odInRejected.getPrCode());
                System.out.println("odRejectedDetails:" + odRejectedDetails);
                List<OdRejectedDetails> list1 = odInRejectedService.selectOdRejectedDetailsList(odRejectedDetails);
                System.out.println("list1" + list1.toString());
                OdPurchaseDetails odPurchaseDetails = new OdPurchaseDetails();
                odPurchaseDetails.setPhCode(odInRejected.getPhCode());
                List<OdPurchaseDetails> list2 = rejectedInfoService.selectOdPurchaseDetailsList(odPurchaseDetails);
                System.out.println("list2:" + list2.toString());
                int count=0;
                for (OdRejectedDetails rejectedDetail : list1) {
                    String rejectedProductCode = rejectedDetail.getProductCode();
                    System.out.println("rejectedProductCode: " + rejectedProductCode);
                    for (OdPurchaseDetails purchaseDetail : list2) {
                        String purchaseProductCode = purchaseDetail.getProductCode();
                        System.out.println("purchaseProductCode: " + purchaseDetail.getPrice());
                        if (rejectedProductCode.trim().equals(purchaseProductCode.trim())) {
                            if (purchaseDetail.getAlreadyNum() == 0 && purchaseDetail.getProductNum() == rejectedDetail.getRejectedNum()) {
                                int nu= odInRejectedService.updateRejectedByCode(0, rejectedDetail.getPrCode(), rejectedDetail.getProductCode());
                                int num = rejectedInfoService.deletePurchaseDetialsByPrCode(purchaseDetail.getPhCode(), purchaseDetail.getProductCode());
                                System.out.println("1");
                                if (num > 0) {
                                    rejectedInfoService.updatePurchase(Math.toIntExact(purchaseDetail.getProductNum()), purchaseDetail.getPhCode());
                                    System.out.println("2");
                                }
                            } else if (purchaseDetail.getAlreadyNum() == 0 && (purchaseDetail.getProductNum()-rejectedDetail.getAlreadyNum()) > rejectedDetail.getRejectedNum()) {
                                int nu=odInRejectedService.updateRejectedByCode(0, rejectedDetail.getPrCode(), rejectedDetail.getProductCode());
                                int num = rejectedInfoService.updatePurchaseDetials(Math.toIntExact((purchaseDetail.getProductNum()-rejectedDetail.getAlreadyNum())- rejectedDetail.getRejectedNum()), purchaseDetail.getPhCode(), purchaseDetail.getProductCode());
                                System.out.println("3");
                                if (num > 0) {
                                    rejectedInfoService.updatePurchase(Math.toIntExact(rejectedDetail.getRejectedNum()), purchaseDetail.getPhCode());
                                    System.out.println("4");
                                }
                            } else if (purchaseDetail.getAlreadyNum()!= 0 && purchaseDetail.getAlreadyNum() < rejectedDetail.getRejectedNum()) {
                                System.out.println("5:"+rejectedDetail);
                                System.out.println("已经退货数量:"+Math.toIntExact(rejectedDetail.getRejectedNum()-((rejectedDetail.getRejectedNum()-(purchaseDetail.getProductNum()-rejectedDetail.getAlreadyNum()))))+"?"+(rejectedDetail.getRejectedNum()-((rejectedDetail.getRejectedNum()-(purchaseDetail.getProductNum()-purchaseDetail.getAlreadyNum()))))+"p"+(rejectedDetail.getRejectedNum()-(purchaseDetail.getProductNum()-rejectedDetail.getAlreadyNum()))+":"+rejectedDetail.getPrCode()+":"+rejectedDetail.getProductCode());
                                int num= odInRejectedService.updateRejectedByCode((int) (rejectedDetail.getRejectedNum()-(purchaseDetail.getProductNum()-rejectedDetail.getAlreadyNum())), rejectedDetail.getPrCode(), rejectedDetail.getProductCode());
                                System.out.println("num:"+num);
                                if(num>0){
                                    System.out.println("进货单修改："+Math.toIntExact(rejectedDetail.getRejectedNum()-((rejectedDetail.getRejectedNum()-(purchaseDetail.getProductNum()-purchaseDetail.getAlreadyNum()))))+":"+purchaseDetail.getPhCode()+":"+purchaseDetail.getProductCode());
                                    int i= rejectedInfoService.updatePurchaseRejectedNum(Math.toIntExact(rejectedDetail.getRejectedNum()-((rejectedDetail.getRejectedNum()-(purchaseDetail.getProductNum()-purchaseDetail.getAlreadyNum())))),purchaseDetail.getPhCode(),purchaseDetail.getProductCode());
                                    System.out.println(i);
                                }
                            }else if (purchaseDetail.getAlreadyNum()!= 0 && rejectedDetail.getRejectedNum() == (purchaseDetail.getProductNum()-purchaseDetail.getAlreadyNum())){
                                //退货数量等于未入库数量
                                //本次退货数量要改 0  当三次完成后  状态改为已完成  进货单的已退货数量要增加
                                count++;
                                int num= odInRejectedService.updateRejectedByCode(0, rejectedDetail.getPrCode(), rejectedDetail.getProductCode());
                                if(num>0){
                                    int i= rejectedInfoService.updatePurchaseRejectedNum(Math.toIntExact(purchaseDetail.getProductNum()-rejectedDetail.getAlreadyNum()),purchaseDetail.getPhCode(),purchaseDetail.getProductCode());
                                }
                            }
                        }
                    }
                }
                if(count==list2.size()){
                    //进货订单的状态变为已完成
                    rejectedInfoService.changePurchaseOrder(odPurchaseDetails.getPhCode());
                    map1.put("pr_state", 4);
                }else {
                    map1.put("pr_state", map.get("result").toString());
                }
            });
        } else {
            map1.put("pr_state", map.get("result").toString());
        }*/
        map1.put("pr_state", map.get("result").toString());
        map1.put("pr_id",list);
        return toAjax(odInRejectedService.checkById(map1));
    }

    @RequiresPermissions("inrejected:inrejected:revoke")
    @RequestMapping("/revoke")
    public AjaxResult revoke(@RequestParam("prId") Integer prId){
        System.out.println("撤回的phid:"+prId);
        return toAjax(odInRejectedService.revokeById(prId));
    }

    @RequiresPermissions("inrejected:inrejected:close")
    @RequestMapping("/colseById")
    public AjaxResult colseById(@RequestParam("prId") Integer prId ){
        return toAjax(odInRejectedService.colseById(prId));
    }

    @RequestMapping("/fileInfo")
    public Map<String,Object> fileInfo(@RequestParam("prcode") String prcode){
        Map<String,Object> map=new HashMap<>();
        PyAttachment pyAttachment=new PyAttachment();
        pyAttachment.setOwnershipNumber(prcode);
        map.put("fileList",pyAttachmentService.selectPyAttachmentList(pyAttachment));
        map.put("orderInfo",rejectedInfoService.selectAllByPrCode(prcode));
        return map;
    }

    @RequestMapping("/selectByCode")
    public Integer selectByCode(@RequestParam("phCode") String phCode){
        System.out.println("selectByCode:"+phCode);
    	return odInRejectedService.selectByCode(phCode);
    }

}
